//
//  ProductViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/12.
//  Copyright © 2016年 guoguo. All rights reserved.
//


#import "ProductViewController.h"


@interface ProductViewController ()<SGTopScrollMenuDelegate, UIScrollViewDelegate>
{
    UIView *viewBanner;
    GuoguoReactionView *chainView;
    UISearchBar * mySearchBar;
    UIView *viewBottom;
    UIView *viewShopping;
    NSInteger numberOfItem;
    UITabBarItem * item;
    UIView *lblLineTop;
    UILabel *lblNoDataShow;
    UIView *viewNoDataShow;
}

@property (nonatomic, strong) SGTopScrollMenu *topScrollMenu;
@property (nonatomic, strong) NSArray *titles;
@property (strong, nonatomic) NSMutableArray<CALayer *> *redLayers;

@end

@implementation ProductViewController
- (NSMutableArray<CALayer *> *)redLayers {
    if (!_redLayers) {
        _redLayers = [NSMutableArray array];
    }
    return _redLayers;
}

- (void)viewWillAppear:(BOOL)animated {

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"全部商品";
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4,0,SCREEN_WIDTH * 3 / 4,40)];
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.placeholder = @"输入关键字进行查找";
    [_searchBar setSearchBarStyle:UISearchBarStyleDefault];
    self.navigationItem.titleView = _searchBar;
    item = [self.tabBarController.tabBar.items objectAtIndex:3];
    globalManager.isAllProduct = YES;
    pageIndex = 1;
    _productCateArr = [[NSMutableArray alloc] init];
    _productChildrenArr = [[NSMutableArray alloc] init];
    _productMainCateArr = [[NSMutableArray alloc] init];
    _productMainCatePathArr = [[NSMutableArray alloc] init];
    _productListArr = [[NSMutableArray alloc] init];
    debugLog(@"%@", globalManager.cateListArr);
    [self loadViewProductCategorys];
    [self initLeftTableView];
    [self initRightTableView];
    if (!globalManager.strKeyName) {
        globalManager.strKeyName = @" ";
    }
    _searchBar.text = globalManager.strKeyName;
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:@"" order:@""];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

}

- (void)initTopNavView {

    self.view.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.topScrollMenu = [SGTopScrollMenu topScrollMenuWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _topScrollMenu.titlesArr = _productMainCateArr;
    _topScrollMenu.topScrollMenuDelegate = self;
     [self.view addSubview:_topScrollMenu];
    
    lblLineTop = [[UIView alloc] initWithFrame:CGRectMake(0, _topScrollMenu.frame.origin.y + _topScrollMenu.frame.size.height, SCREEN_WIDTH, 2)];
    lblLineTop.backgroundColor = [UIColor whiteColor];
    lblLineTop.layer.borderWidth = 1.0f;
    lblLineTop.layer.borderColor = EastMarket_hintFontColor.CGColor;
    lblLineTop.viewBorder = viewBorderBottom;
    [self.view addSubview:lblLineTop];
}

- (void)initGuideBanner {
    chainView = [[GuoguoReactionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TopBarHeight)];
    [self.view addSubview:chainView];
}

// 添加常用料
- (void)callServerCustomerAdd:(NSString *)itemId {

    NSDictionary *resultOfCustomerAdd = [AppServiceInterface CustomerItemAdd:itemId];
    [self performSelectorOnMainThread:@selector(updateUIAfterCustomerAdd:) withObject:resultOfCustomerAdd waitUntilDone:NO];
}

- (void)updateUIAfterCustomerAdd:(NSDictionary *)dic {

    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        [GlobalUnit showMessage:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
        [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
    } else if (dic && [[dic objectForKey:@"success"] integerValue] == 0) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

// 取消常用料
- (void)callServerCustomerDelete:(NSString *)itemId {
    
    NSDictionary *resultOfCustomerDel = [AppServiceInterface CustomerItemDelete:itemId];
    [self performSelectorOnMainThread:@selector(updateUIAfterCustomerAdd:) withObject:resultOfCustomerDel waitUntilDone:NO];
}

// 分类请求
- (void)loadViewProductCategorys {
    
    [NSThread detachNewThreadSelector:@selector(callServerGetProductCategorys) toTarget:self  withObject:Nil];
}

- (void)callServerGetProductCategorys {
    
    NSDictionary *dicOfProductCate = [AppServiceInterface getProductCate];
    [self performSelectorOnMainThread:@selector(updateProductCate:) withObject:dicOfProductCate waitUntilDone:NO];
}

- (void)updateProductCate:(NSDictionary *)dic {
    
    [SVProgressHUD dismiss];

    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if ([[dic objectForKey:@"code"] isEqualToString:@"LoginRequire"]) {
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:true];
            return;
        }
        [_productMainCateArr addObject:@"全部"];
        [_productCateArr addObjectsFromArray:[dic objectForKey:@"data"]];
        for (NSDictionary *dic in _productCateArr) {
            [_productMainCateArr addObject:[dic objectForKey:@"name"]];
            [_productMainCatePathArr addObject:[dic objectForKey:@"path"]];
        }
        [self initTopNavView];
    } else if(dic && [[dic objectForKey:@"success"] integerValue] != 1) {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

// 添加商品到购物车
- (void)loadViewCartItem:(NSString *)productID productNum:(NSInteger)productNum {

    _strProductID = productID;
    _productNum = productNum;
    [NSThread detachNewThreadSelector:@selector(callServerGetPCartItem) toTarget:self  withObject:Nil];
}

- (void)callServerGetPCartItem {

    NSDictionary *dict = [AppServiceInterface cartItem:_strProductID itemNum:_productNum];
     [self performSelectorOnMainThread:@selector(updateCartItem:) withObject:dict waitUntilDone:NO];
}

- (void)updateCartItem:(NSDictionary *)dic {

    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSNull class]]) {
//            [_tvDetailList reloadData];
            item.badgeValue = [NSString stringWithFormat:@"%@", [[dic objectForKey:@"data"] objectForKey:@"cartItemNum"]];
            [NSThread detachNewThreadSelector:@selector(updateProductListOfSearch) toTarget:self  withObject:Nil];
            
        }
    }
}

- (void)updateProductListOfSearch {

    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}
// 关键字搜索
- (void)loadViewProductListOfSearch:(NSString *)keyName productCatePath:(NSString *)productCatePath order:(NSString *)order {
//    globalManager.strKeyName = keyName;
    strProductCatePath = productCatePath;
    strOrder = order;
    
    [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
}

- (void)loadNewData {
    
    pageIndex = 1;
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}

- (void)loadMoreData {
    
    pageIndex += 1;
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}

- (void)callServerProductListOfSearch {
    
    pageSize = 20;
    NSDictionary *dicOfProductCate = [AppServiceInterface productOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder page:pageIndex pageSize:pageSize];
    [self performSelectorOnMainThread:@selector(updateProductListOfSearch:) withObject:dicOfProductCate waitUntilDone:NO];
}

- (void)updateProductListOfSearch:(NSDictionary *)dic {
    
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if ([[[dic objectForKey:@"data"] objectForKey:@"page"] integerValue] == 1) {
            [_productListArr removeAllObjects];
        }
        [_productListArr addObjectsFromArray:[[dic objectForKey:@"data"] objectForKey:@"results"]];
        if (_productListArr.count < 1) {
            viewNoDataShow.hidden = NO;
        } else {
            
            viewNoDataShow.hidden = YES;
        }

//        [_tvCategoryList reloadData];
        [_tvDetailList reloadData];
        
        [_tvDetailList.mj_header endRefreshing];
        [_tvDetailList.mj_footer endRefreshing];
        if ([[[dic objectForKey:@"data"] objectForKey:@"total"] intValue] <= [[[dic objectForKey:@"data"] objectForKey:@"pageSize"] intValue] * ([[[dic objectForKey:@"data"] objectForKey:@"page"] intValue])) {
            debugLog(@"*****************************************************");
            [_tvDetailList.mj_footer endRefreshingWithNoMoreData];
        }
        
    } else if(dic && [[dic objectForKey:@"success"] integerValue] == 0) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务为失败，请稍后重试"];
    }
}

- (void)initLeftTableView {
    
    CGFloat tvCategoryCellHeight = 44.0f;
    //左边分类列表
    self.tvCategoryList = [[UITableView alloc] initWithFrame:CGRectMake(0, 46, self.view.frame.size.width / 4, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - 46) style:UITableViewStylePlain];
    self.tvCategoryList.backgroundColor = EastMarket_backgroundColor;
    self.tvCategoryList.rowHeight = tvCategoryCellHeight;
//    [self.tvCategoryList setSeparatorColor:EastMarket_darkGreyFontColor];
    self.tvCategoryList.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setExtraCellLineHidden:self.tvCategoryList];
    [self.view addSubview:self.tvCategoryList];
    self.tvCategoryList.delegate = self;
    self.tvCategoryList.dataSource = self;
    self.tvCategoryList.hidden = YES;
}

- (void)initRightTableView {
    CGFloat tvDetailCellHeight = 110.0f;
    // 右边商品列表
    self.tvDetailList = [[UITableView alloc] initWithFrame:CGRectMake(0, 46, SCREEN_WIDTH, SCREEN_HEIGHT  - TopBarHeight - TabBarHeight - 46) style:UITableViewStylePlain];
    self.tvDetailList.backgroundColor = EastMarket_backgroundColor;
    self.tvDetailList.rowHeight = tvDetailCellHeight;
    [self setExtraCellLineHidden:self.tvDetailList];
    [self.tvDetailList setSeparatorColor:EastMarket_bordColor];
    [self.view addSubview:self.tvDetailList];
    self.tvDetailList.delegate = self;
    self.tvDetailList.dataSource = self;
    
    self.tvDetailList.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // Enter the refresh status immediately
    //[_tabView.mj_header beginRefreshing];
    self.tvDetailList.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

    
    viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH, TabBarHeight)];
    viewBottom.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewBottom];
    [self.view bringSubviewToFront:viewBottom];
    
    viewShopping = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 3 / 5, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH / 5, TabBarHeight)];
    viewShopping.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewShopping];
    
    viewNoDataShow = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 4, 46, SCREEN_WIDTH * 3 / 4, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - 46)];
    viewNoDataShow.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewNoDataShow];
    lblNoDataShow = [[UILabel alloc] initWithFrame:CGRectMake(8, SCREEN_HEIGHT / 4, viewNoDataShow.frame.size.width - 16, 22)];
    lblNoDataShow.text = @"抱歉没有找到符合条件的菜品";
    lblNoDataShow.textAlignment = NSTextAlignmentCenter;
    lblNoDataShow.font = [UIFont systemFontOfSize:14];
    [viewNoDataShow addSubview:lblNoDataShow];
    viewNoDataShow.hidden = YES;
}

#pragma mark -- UITableViewDelegate &  UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _tvCategoryList) {
        return _productChildrenArr.count;
    } else {
    
        return _productListArr.count;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (tableView == _tvCategoryList) {
        NSInteger curRow = [indexPath row];
        NSDictionary *childrenCateDict = [_productChildrenArr objectAtIndex:curRow];
        strProductCatePath = [NSString stringWithFormat:@"%@", [childrenCateDict objectForKey:@"path"]];
        [_productListArr removeAllObjects];
        debugLog(@"strProductCatePath:%@", strProductCatePath);
        if ([strProductCatePath isEqualToString:@"(null)"]) {
            strProductCatePath = @" ";
        }
        [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:@""];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    static NSString *categorIdentifier = @"category";
    static NSString *detailIdentifier = @"detail";
    if (tableView == _tvCategoryList) {
        CategoryLeftViewCell *categoryCell = [tableView cellForRowAtIndexPath:indexPath];
        if (categoryCell == nil) {
            categoryCell = [[CategoryLeftViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:categorIdentifier];
        }
//        cell = categoryCell;
        categoryCell.lblTitle.font = [UIFont systemFontOfSize:12];
        NSInteger curRow = [indexPath row];
        NSDictionary *childrenCateDict = [_productChildrenArr objectAtIndex:curRow];
        categoryCell.lblTitle.text = [NSString stringWithFormat:@"%@", [childrenCateDict objectForKey:@"name"]];
        categoryCell.lblTitle.font = [UIFont systemFontOfSize:14];
        categoryCell.lblTitle.textColor = [UIColor darkGrayColor];
        categoryCell.lblTitle.textAlignment = NSTextAlignmentCenter;
        categoryCell.lblTitle.numberOfLines = 0;
//        if (categoryCell.isSelected) {
//            categoryCell.lblTitle.layer.borderColor = EastMarket_MainToneColor.CGColor;
//            categoryCell.lblTitle.viewBorder = viewBorderLeft;
//        }
        debugLog(@"*********%@", cell.textLabel.text);
        categoryCell.backgroundColor = EastMarket_UnderlineColor;
        categoryCell.selectedBackgroundView = [[UIView alloc] initWithFrame:categoryCell.frame];
        categoryCell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
        categoryCell.selectedBackgroundView.layer.borderColor = EastMarket_MainToneColor.CGColor;
        categoryCell.selectedBackgroundView.viewBorder = viewBorderLeft;
        
//        CALayer *bottomBorder = [CALayer layer];
//        float height = categoryCell.selectedBackgroundView.frame.size.height - 1.0f;
//        float width = categoryCell.selectedBackgroundView.frame.size.width;
//        bottomBorder.frame = CGRectMake(0.0f, height, width, 1.0f);
//        bottomBorder.backgroundColor =  EastMarket_hintFontColor.CGColor;
//        [categoryCell.selectedBackgroundView.layer addSublayer:bottomBorder];

        return categoryCell;
    } else {
        
        ProductOrMaterialsViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil) {
            cell = [[ProductOrMaterialsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:detailIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
        
        NSInteger curRow = [indexPath row];
        NSDictionary *productListDict;
        if (_productListArr.count > 0) {
          productListDict = [_productListArr objectAtIndex:curRow];
        }
        
        [cell.imgProductIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [productListDict objectForKey:@"itemPic"]]] placeholderImage:[UIImage imageNamed:@"NoProductImage"]];
        cell.lblProductName.text = [NSString stringWithFormat:@"%@", [productListDict objectForKey:@"title"]];
        cell.lblProductPrice.text = [NSString stringWithFormat:@"%.2lf元", [[productListDict objectForKey:@"itemPrice"] floatValue]];
        if (![[productListDict objectForKey:@"originalPrice"] isKindOfClass:[NSNull class]]) {
            cell.lblOriginalPrice.text = [NSString stringWithFormat:@"%.2lf元", [[productListDict objectForKey:@"originalPrice"] floatValue]];
            //中划线
            NSDictionary *attribtDic =@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%.2lf元", [[productListDict objectForKey:@"originalPrice"] floatValue]] attributes:attribtDic];
            cell.lblOriginalPrice.attributedText = attribtStr;
        }

        cell.lblProductSupplier.text = [NSString stringWithFormat:@"%@", [productListDict objectForKey:@"sellerName"]];
        cell.lblProductNum.text = [NSString stringWithFormat:@"%ld", [[productListDict objectForKey:@"cartNum"] integerValue]];
        _favor = [NSString stringWithFormat:@"%@", [productListDict objectForKey:@"favor"]];
        NSString *itemStr = [NSString stringWithFormat:@"%@", [productListDict objectForKey:@"id"]];
        if (_favor.integerValue == 0) {
            [cell.btnFavorite setBackgroundImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
        } else if(_favor.integerValue == 1){
        
            [cell.btnFavorite setBackgroundImage:[UIImage imageNamed:@"star-active"] forState:UIControlStateNormal];
        }
        numberOfItem = [[productListDict objectForKey:@"cartNum"] integerValue];
        cell.block=^(CGPoint point)
        {
            
            CGPoint startPoint = [self.view convertPoint:point fromView:self.tvDetailList];
            
            CGPoint endpoint=[self.view convertPoint:viewShopping.center fromView:viewBottom];
            [self initCHLayerFromPoint:startPoint toPoint:endpoint];
        };

        cell.btnFavoriteClick = ^() {
            
            debugMethod();
            if (_favor.integerValue == 0) {
                [NSThread detachNewThreadSelector:@selector(callServerCustomerAdd:) toTarget:self  withObject:itemStr];
                [_tvDetailList reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            } else if(_favor.integerValue == 1){
                
                UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"温馨提示！" message:@"您确定要取消当前收藏商品吗？" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [NSThread detachNewThreadSelector:@selector(callServerCustomerDelete:) toTarget:self  withObject:itemStr];
                    [_tvDetailList reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }];
                
                [alerController addAction:cancleAction];
                [alerController addAction:defaultAction];
                [self  presentViewController:alerController animated:YES completion:nil];
            }
        };
        cell.btnNumReduceClick = ^() {
            
            debugMethod();
            debugLog(@"%ld", indexPath.row);
            if (cell.lblProductNum.text.integerValue > 0) {
                numberOfItem -= 1;
                [_tvDetailList reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
                [self loadViewCartItem:[NSString stringWithFormat:@"%@", [productListDict objectForKey:@"id"]] productNum:-1];
            } else {
            
                [GlobalUnit showAlertHint:@"温馨提示！" message:@"当前商品数目为0"];
            }
        };
        
        cell.btnNumAddClick = ^() {
            
            debugMethod();
            debugLog(@"%ld", indexPath.row);
            numberOfItem += 1;
            [_tvDetailList reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self loadViewCartItem:[NSString stringWithFormat:@"%@", [productListDict objectForKey:@"id"]] productNum:1];
        };
        return cell;
    }
    return cell;

}
- (void)SGTopScrollMenu:(SGTopScrollMenu *)topScrollMenu didSelectTitleAtIndex:(NSInteger)index{
    
    if (index == 0) {
        self.tvCategoryList.hidden = YES;
        self.tvDetailList.frame = CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - 44);
        globalManager.isAllProduct = true;
    } else {
        self.tvCategoryList.hidden = NO;
        self.tvDetailList.frame = CGRectMake(SCREEN_WIDTH / 4, 44, SCREEN_WIDTH * 3 / 4, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - 44);
        globalManager.isAllProduct = false;
    }
    
    [_productChildrenArr removeAllObjects];
    NSDictionary* all = @{ @"parentId": @"-1", @"name": @"全部产品" };
    [_productChildrenArr addObject:all];
    [_productListArr removeAllObjects];

    for (NSDictionary *dictCate in _productCateArr) {
        if ([[dictCate objectForKey:@"name"] isEqualToString:_productMainCateArr[index]]) {
            [_productChildrenArr addObjectsFromArray:[dictCate objectForKey:@"children"]];
            [_tvCategoryList reloadData];
        }
    }
    strProductCatePath = [NSString stringWithFormat:@"%@", _productMainCatePathArr[index]] ;
    debugLog(@"%@", strProductCatePath);
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:[NSString stringWithFormat:@"%@", _productMainCatePathArr[index]] order:@""];
}

//多余的空行上不显示分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

#pragma mark --  UISearchBarDelegate & UISearchResultsUpdating delegate
// 取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    debugMethod();
    [_searchBar resignFirstResponder];
    _searchBar.showsCancelButton = false;
    _searchBar.text = nil;
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}
// 搜索按钮点击的回调
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    debugMethod();
    [_searchBar resignFirstResponder];
//    globalManager.strKeyName = _searchBar.text;
    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    debugMethod();
    _searchBar.showsCancelButton = true;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    debugMethod();
    return YES;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    debugMethod();
//    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    [self loadViewProductListOfSearch:_searchBar.text productCatePath:strProductCatePath order:strOrder];
}

- (void)initCHLayerFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {
    
    CALayer *chLayer = [[CALayer alloc] init];
    [self.redLayers addObject:chLayer];
    
    chLayer.frame = CGRectMake(startPoint.x, startPoint.y, 15, 15);
    chLayer.cornerRadius = CGRectGetWidth(chLayer.frame)/2.f;
    chLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:chLayer];
    
    CAKeyframeAnimation *CHAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddQuadCurveToPoint(path, NULL, endPoint.x, startPoint.y, endPoint.x, endPoint.y);
    
    CHAnimation.path = path;
    CHAnimation.removedOnCompletion = NO;
    CHAnimation.fillMode = kCAFillModeBoth;
    CHAnimation.duration = 0.5;
    CHAnimation.delegate = self;
    [chLayer addAnimation:CHAnimation forKey:nil];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    [self.redLayers[0] removeFromSuperlayer];
    [self.redLayers removeObjectAtIndex:0];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
